<template>
  <v-layout :title="title">

    <orderList

      :right-data.sync="rightData"
      :total-money1.sync="totalMoney"
      desc="收款"
      @next1="next1"
      @rightDataChange="rightDataChange"
    />

    <!--付款银行信息-->
    <vRemitBank
      :remit-bank="remitBank"
      :advertiser_id="advertiser_id"
      @remitBankChange="remitBankChange"
    />

    <!--收款银行信息-->
    <receiptBank
      :total-money="totalMoney"
      :receipt-bank-data="receiptBankData"
      @selectChange="receiptBankChange"
    />

    <!--发送给商务-->
    <sendMessage
      v-if="financeRole&&rightData.length===0"
      :claimed-member="claimedMember"
      @select="onSelectedBusiness"
      @sendMessage="handleSendMessage"
    />

    <!--开票进度-->
    <el-row
      v-if="messages.length">
      <div class="subtitle">
        开票进度查看：
      </div>
      <v-messageBox
        :messages="messages"
      />
    </el-row>

    <!--按钮-->
    <!--商务显示按钮-->
    <!--<el-row type="flex" justify="end" class="pdv15 pdr120" v-if="businessRole">-->
    <!--<el-button type="primary" size="small" @click="back">返回</el-button>-->
    <!--<el-button type="primary" size="small" @click="submit(1)">提交给财务</el-button>-->
    <!--</el-row>-->
    <!--财务显示按钮-->
    <el-row v-if="financeRole&&rightData.length!==0&&mp_id" type="flex" justify="end" class="pdv15 pdr120">
      <!--<el-button type="primary" size="small" @click="back">返回</el-button>-->
      <el-button type="primary" size="small" @click="check(3)">退回,审核不通过</el-button>
      <el-button type="primary" size="small" @click="check(4)">确认,审核通过</el-button>
    </el-row>
    <el-row v-if="financeRole&&rightData.length!==0&&!mp_id" type="flex" justify="end" class="pdv15 pdr120">
      <el-button type="primary" size="small" @click="submit(4)">确认,审核通过</el-button>
    </el-row>

  </v-layout>
</template>

<script>
import auth from '@/mixins/auth'
import orderList from '../components/order_list'
import sendMessage from '../components/send_message'
import receiptBank from '../components/receipt_bank'
import vRemitBank from '../components/remit_bank'

export default {
  components: {
    orderList,
    sendMessage,
    receiptBank,
    vRemitBank
  },
  mixins: [auth],
  data() {
    console.log(Number(''),+' ');
    return {
      mp_id: '',
      state4: '',
      timeout: null,

      rightData: [],
      totalMoney: 0,
      claimedMember: [],
      // 付款银行信息
      remitBank: {},

      businessList: [],
      receiptBankData: {},

      warningList: [],
      // 历史记录
      messages: []

    }
  },
  computed: {
    title() {
      if (this.mp_id) {
        return '修改收款信息'
      } else {
        return '创建收款信息'
      }
    },
    // 广告主id
    advertiser_id() {
      console.log(this.rightData)
      if (!this.rightData.length) {
        return 0
      }

      return this.rightData[0].advertiser_id
    },

    moneyWarning() {
      return (+this.totalMoney !== +this.receiptBankData.money)
    }
  },
  watch: {
    totalMoney(val) {
      this.receiptBankData.receipt_money = val||0
    }
  },
  activated() {
    this.mp_id = this.$route.query.id
    if (this.$route.query.order) {
      const data = JSON.parse(this.$route.query.order)
      data.rest_money = +data.ad_price - data.real_price
      if (data.money) {
        return data
      }
      data.money = data.rest_money
      this.$set(this.rightData, 0, data)
    }

    this.$route.query.id && this.getReconcileDetail()
  },
  methods: {
    // 获取对账单详情
    getReconcileDetail() {
      const loading = this.$loading()
      const data = { mp_id: this.mp_id }
      this.$get('action/CheckingRequisition/qryOp', data)
        .then(res => {
          console.log(res, 'ads')
          this.rightData = res.data.Advs.map((item, index) => {
            const data = item
            data.rest_money = +data.ad_price - data.real_price||0
            if (data.money) {
              return data
            }
            data.money = data.rest_money
            return data
          })
          this.messages = res.data.CheckReqLogInfo
          const details = res.data.checkingrequisition.length && res.data.checkingrequisition[0] || {}
          this.remitBank = details.adv_bank_info && JSON.parse(details.adv_bank_info) || {}
          this.receiptBankData = details
          this.claimedMember = res.data.claimrecord.map(item => {
            const obj = {}
            obj.name = item.name
            obj.id = item.id
            obj.status = item.gender
            return obj
          })
          loading.close()
        })
        .catch(_=>{
          loading.close()
        })
    },

    onSelectedBusiness(val) {
      this.businessList = val.map(item => {
        return item.id
      })
    },
    handleSendMessage() {
      if (this.receiptBankData.name && this.receiptBankData.money && this.businessList.length) {
        const url = this.$route.query.id ? 'action/CheckingRequisition/update' : 'action/CheckingRequisition/save'
        const data = {
          invoiceinfo_id: this.receiptBankData.id,
          money: this.receiptBankData.money,
          notes: this.receiptBankData.notes,
          ClaimRecordlist: this.businessList.toString(),
          cur_status: 0,
          id: this.mp_id
        }
        this.$post(url, data)
          .then(res => {
            new Promise((resolve, reject) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              resolve()
            }).then(_ => this.$router.go(-1))
          })
      } else {
        this.$alert('请填写收款银行, 收款金额并选择通知人', '提示', {
          confirmButtonText: '确定'
        })
      }
    },

    // 收款银行改变
    receiptBankChange(val) {
      this.receiptBankData.id = val.id
      // this.receiptBankData.id = val.id;
    },
    // 汇款银行信息改变
    remitBankChange(val) {
      this.remitBank = val
    },

    // 通过审核: 1.提交给财务 2.财务通过审核
    submit(val) {
      if (this.moneyWarning) {
        this.$alert('本次收款金额不等于订单总金额无法通过审核', '提示', {
          confirmButtonText: '确定'
        })
      } else {
        this.submitOrder(val)
      }
    },
    submitOrder(val) {
      let data
      const orderList = this.rightData.map(item => {
        const data = {}
        data.adv_id = item.ad_id
        data.money = item.money
        return data
      })
      data = {
        cur_status: val,
        // advertiser_id: this.advertiser_id || 0,
        adv_bank_info: JSON.stringify(this.remitBank),
        CheckReqLogInfo: JSON.stringify({ CRLlist: orderList }),
        invoiceinfo_id: this.receiptBankData.id,
        invoiceinfo_account: this.receiptBankData.accounts,
        invoiceinfo_bank: this.receiptBankData.openbank,
        money: this.receiptBankData.receipt_money,
        notes: this.receiptBankData.notes,
        staff_id: this.rightData.length ? this.rightData[0].swid : ''
      }
      this.$post('action/CheckingRequisition/save', data)
        .then(res => {
          new Promise((resolve, reject) => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            resolve()
          }).then(_ => this.$router.go(-1))
        })
    },

    check(val) {
      const orderList = this.rightData.map(item => {
        const data = {}
        data.adv_id = item.ad_id
        data.money = item.money
        return data
      })
      const data = {
        cur_status: val,
        id: this.mp_id,
        advertiser_id: this.advertiser_id || 0,
        adv_bank_info: JSON.stringify(this.remitBank),
        CheckReqLogInfo: JSON.stringify({ CRLlist: orderList }),
        invoiceinfo_id: this.receiptBankData.id,
        invoiceinfo_account: this.receiptBankData.accounts,
        invoiceinfo_bank: this.receiptBankData.openbank,
        money: this.receiptBankData.money,
        notes: this.receiptBankData.notes,
        staff_id: this.rightData.length ? this.rightData[0].swid : ''
      }
      switch (val) {
        case 4:
          if (this.moneyWarning) {
            this.$alert(`本次收款金额不等于订单总金额无法通过审核`, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              return
            })
          } else {
            this.$post('action/CheckingRequisition/update', data)
              .then(res => {
                new Promise((resolve, reject) => {
                  this.$message({
                    message: res.msg,
                    type: 'success'
                  })
                  resolve()
                }).then(_ => this.$router.go(-1))
              })
          }
          break
        default:
          this.$post('action/CheckingRequisition/update', data)
            .then(res => {
              new Promise((resolve, reject) => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                resolve()
              }).then(_ => this.$router.go(-1))
            })
          break
      }
    },

    rightDataChange(val) {
      console.log(val)
      // this.rightData = val.row||[]
    },

    back() {
      this.$router.go(-1)
    },
    next1(rightData, totalMoney) {
      this.receiptBankData.money = this.totalMoney
    }
  }
}
</script>

<style scoped>
    .flex-box {
        flex-wrap: wrap;
    }

    span + button {
        margin-left: 15px
    }

</style>
<style>
    .my-date-picker .el-date-editor--daterange.el-input__inner {
        width: 100%;
        min-width: 200px;
    }

    .datepicker {
        overflow: scroll;
        min-width: 375px;
    }

    .btn {
        padding: 5px 8px;
    }

    .btn + .btn {
        margin-left: 5px
    }

    .el-card__body:after {
        content: '';
        display: block;
        clear: both
    }
</style>
